/*
 * Copyright 2012 the purple river software Co., Ltd.
 * 
 * http://www.purple-river.com
 */
package com.jqd.framework.core.hessian.web.controller;

import org.springframework.context.ApplicationContext;

import com.jqd.framework.core.exception.WebControllerException;
import com.jqd.framework.core.hessian.model.ServiceRequest;
import com.jqd.framework.core.hessian.model.ServiceResponse;
import com.jqd.framework.core.spring.context.ApplicationContextFactory;
import com.jqd.framework.util.Assert;

/**
 * 
 * TODO
 * 
 * @author liaozhicheng@purple-river.com
 * @date 2012-3-21
 * @since 1.0
 */
public class DispatchServiceSupport implements DispatchService {
	
	public ServiceResponse doDispatch(ServiceRequest serviceRequest) throws WebControllerException {
		
		return doDispatch(serviceRequest, DEFAULT_DISPATCH_SERVICE_NAME);
	}
	
	
	public ServiceResponse doDispatch(ServiceRequest serviceRequest, final String serviceName)
			throws WebControllerException {
		
		Assert.notNull(serviceRequest, "Parameter 'serviceRequest' can not be null");
		Assert.hasText(serviceName, "Parameter 'serviceName' can not be null or empty");
		
		ServiceResponse serviceResponse = null;
		
		try {
			ApplicationContext ctx = ApplicationContextFactory.getCurrentApplicationContext();
			
			// 1）如果controller和action在同一个应用中，则这里getBean()方法返回的
			// 是ApplicationControllerHandler接口的一个具体实现类；
			// 2）如果controller和action不在同一个应用中，则这里getBean()返回的是一个代理对象
			ApplicationControllerHandler handler = (ApplicationControllerHandler) ctx
					.getBean(serviceName);
			serviceResponse = handler.handleRequest(serviceRequest);
		}
		catch (Exception ex) {
			throw new WebControllerException(ex);
		}
		
		return serviceResponse;
	}
	
}
